package com.lkdont.cameratest

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import androidx.navigation.Navigation
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lkdont.android.base.ui.BaseFrag
import com.lkdont.android.media.examples.R
import kotlinx.android.synthetic.main.frag_example_list.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import kotlin.coroutines.resume

private class ExampleAdapter(
    private val exampleList: List<String>,
    private val onItemClickListener: (itemView: View, example: String) -> Unit
) : RecyclerView.Adapter<ExampleAdapter.ExampleHolder>() {

    class ExampleHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val text: TextView = itemView.findViewById(android.R.id.text1)
    }

    override fun getItemCount() = exampleList.size

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        ExampleHolder(
            LayoutInflater.from(parent.context)
                .inflate(android.R.layout.simple_list_item_1, parent, false)
        )

    override fun onBindViewHolder(holder: ExampleHolder, position: Int) {
        val example = exampleList[position]
        holder.text.text = example
        holder.itemView.setOnClickListener {
            onItemClickListener(holder.itemView, example)
        }
    }
}

private const val EXAMPLE_TAKE_PHOTO = "Take Photo"
private const val EXAMPLE_TAKE_VIDEO = "Take Video"

/**
 * 例子列表页面
 *
 * @author lqd
 */
class ExampleListFrag : BaseFrag() {

    companion object {
        private val TAG = ExampleListFrag::class.java.simpleName
    }

    private val navController: NavController by lazy {
        Navigation.findNavController(requireActivity(), R.id.nav_host_fragment)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.frag_example_list, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        exampleRv.apply {
            layoutManager = LinearLayoutManager(requireContext())
            adapter =
                ExampleAdapter(arrayListOf(EXAMPLE_TAKE_PHOTO, EXAMPLE_TAKE_VIDEO)) { _, example ->
                    when (example) {

                        EXAMPLE_TAKE_PHOTO -> {
                            navController.navigate(ExampleListFragDirections.actionExampleListFragToTakePhotoFrag())
                        }

                        EXAMPLE_TAKE_VIDEO -> {
                            navController.navigate(ExampleListFragDirections.actionExampleListFragToTakeVideoFrag())
                        }

                        else -> {
                            throw IllegalStateException("Unknown example : $example")
                        }
                    }
                }
        }

//        Log.w(TAG, "onViewCreated: testCoroutine start")
//        testCoroutine()
//        Log.w(TAG, "onViewCreated: testCoroutine end")
    }

//    private suspend fun testCancelable1() = suspendCancellableCoroutine<Int> { cont ->
//        Log.i(TAG, "testCancelable1: start " + Thread.currentThread().name)
//        var result = 0
//        run loop@{
//            (1..100).forEach {
//                result += it
//                if (result > 2000) {
//                    Log.d(TAG, "testCancelable1: cancel result=$result")
//                    cont.cancel(IllegalStateException("test cancel"))
//                    return@loop
//                }
//                Thread.sleep(100)
//            }
//        }
//        Log.i(
//            TAG,
//            "testCancelable1: end before resume isActive=${cont.isActive}, isCancelled=${cont.isCancelled}, isCompleted=${cont.isCompleted}"
//        )
//        if (cont.isActive) cont.resume(result)
//        Log.i(TAG, "testCancelable1: end after resume")
//    }
//
//    /** 测试协程 */
//    private fun testCoroutine() = lifecycleScope.launch(Dispatchers.Main) {
//        Log.d(TAG, "testCoroutine: start Thread=${Thread.currentThread().name}")
//        withContext(Dispatchers.IO) {
//            val result = try {
//                testCancelable1()
//            } catch (t: Throwable) {
//                -1
//            }
//            Log.d(TAG, "testCoroutine: result=$result ${Thread.currentThread().name}")
//        }
//        Log.d(TAG, "testCoroutine: end")
//    }
}
